今天來用react hook寫一個投骰子遊戲~
一樣以 codesandbox 作為環境
先上傳六張骰子點數的圖片
增加 Dash.js 用來顯示主要的遊戲狀態,Dice.js 顯示當下骰子投出的點數
Dash.js 照慣例 import useState , useEffect 這幾個 react hook
及依序 import 圖片資源
import { useEffect, useState } from "react";
import Dice from "./Dice.js";
// import dice images
import dice1 from "./img/dice1.jpg";
import dice2 from "./img/dice2.jpg";
import dice3 from "./img/dice3.jpg";
import dice4 from "./img/dice4.jpg";
import dice5 from "./img/dice5.jpg";
import dice6 from "./img/dice6.jpg";
export default function Dash() {
const [diceSrc, setDiceImg] = useState(dice1);
const [diceNum, setDiceNUum] = useState(null);
return (
<>
<Dice diceNumber={"0"} diceSrc={diceSrc} />
<button
onClick={() => {
let gameRes = generateDiceNumber();
setDiceImg(gameRes.src);
setDiceNUum(gameRes.diceNumber);
}}
>
投骰子
</button>
</>
);
}
Dice.js
Dice component 僅顯示 parent component 傳來 props
import "./Dice.css";
function Dice(props) {
const { diceSrc } = props;
console.log(diceSrc);
return (
<div className="dice">
<img className="dice-img" src={diceSrc} alt="dice" />
</div>
);
}
export default Dice;
順便寫一下 Dice 簡單的樣式
Dice.css
.dice {
border: 4px solid #222;
border-radius: 20px;
width: 140px;
height: 140px;
overflow: hidden;
}
.dice-img {
max-width: 100%;
}
在 Dash component 內補上產生隨機點數的函式 generateDiceNumber
export default function Dash() {
const [diceSrc, setDiceImg] = useState(dice1);
const [diceNum, setDiceNum] = useState(null);
function generateDiceNumber() {
let randomize = Math.ceil(Math.random() * 6);
let diceResult;
switch (randomize) {
case 1: {
diceResult = dice1;
break;
}
case 2: {
diceResult = dice2;
break;
}
case 3: {
diceResult = dice3;
break;
}
case 4: {
diceResult = dice4;
break;
}
case 5: {
diceResult = dice5;
break;
}
default: {
diceResult = dice6;
}
}
// return diceResult;
return { diceNumber: randomize, src: diceResult };
}
useEffect(() => {
generateDiceNumber();
}, [diceSrc]);
return (
<>
<Dice diceNumber={"0"} diceSrc={diceSrc} />
<button
onClick={() => {
let gameRes = generateDiceNumber();
setDiceImg(gameRes.src);
setDiceNum(gameRes.diceNumber);
setStart(true);
}}
>
投骰子
</button>
</>
);
}
這時候,點擊 投骰子 的按鈕就可以看到確實生成隨機的骰子點數了
今天的codesandbox在這裡
接下來繼續新增